package com.tyc.threadlocal;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 测试ThreadLocal内存泄露
 * 查看线程池中各个线程threadLocals中table里的数据
 * 发现弱引用referent为nul被回收而value还存在
 * 关于内存泄露 https://www.cnblogs.com/onlywujun/p/3524675.html
 * @author tyc
 * @version 1.0
 * @date 2021-08-26 10:35:53
 */
public class ThreadLocalTest2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        ExecutorService executors = Executors.newFixedThreadPool(1);

        executors.execute(new Thread(()->{
            ThreadLocal<Object> threadLocal = new ThreadLocal<>();
            threadLocal.set("1111111111111111111");
            System.out.println(threadLocal.get());
            countDownLatch.countDown();
        }));


        executors.execute(new Thread(()->{
            ThreadLocal<Object> threadLocal = new ThreadLocal<>();
            threadLocal.set("222222222222222222222");
            System.out.println(threadLocal.get());
            countDownLatch.countDown();
        }));

        executors.execute(()->{
            ThreadLocal<Object> threadLocal = new ThreadLocal<>();
            threadLocal.set("3333333333333333333");
            System.out.println(threadLocal.get());
            countDownLatch.countDown();
        });

        countDownLatch.await();
        System.gc();

        System.out.println("end");
    }
}
